/*
 * @文件描述: 验证文件
 * @公司: 山东大学信息学院
 * @作者: 李洪文
 * @Date: 2019-10-11 16:32:55
 * @LastEditors  : 李洪文
 * @LastEditTime : 2019-12-18 19:57:07
 */
import regexUtils from '../utils/regex-utils';

export const MAX_LENGTH_USERNAME = 20;
export const MAX_LENGTH_PASSWORD = 15;
export const MIN_LENGTH_PASSWORD = 6;
export const MAX_LENGTH_TITLE = 50;
export const MAX_LENGTH_DESC = 200;
export const MAX_LENGTH_COMMENT = 100;
export const MAX_LENGTH_PHONE = 11;
export const MAX_LENGTH_SMS = 6;

/*策略对象*/
const strategies = {
  isNonEmpty(value: string, errorMsg: string) {
    return value === '' || value === 'undefined' || value === 'null' ? errorMsg : void 0;
  },
  minLength(value: string, length: number, errorMsg: string) {
    return value.length < length ? errorMsg : void 0;
  },
  isMoblie(value: string, errorMsg: string) {
    return !regexUtils.isPhone(value) ? errorMsg : void 0;
  },
  isEmail(value: string, errorMsg: string) {
    return !regexUtils.isEmail(value) ? errorMsg : void 0;
  },
};

interface ValidatorFunc {
  (): boolean;
}

export class Validator {
  public cache: ValidatorFunc[] = []; //保存校验规则

  public add(value: string, rules: { strategy: string; errorMsg: string }[]) {
    for (const rule of rules) {
      const strategyAry: string[] = rule.strategy.split(':'); //例如['minLength',6]
      const errorMsg = rule.errorMsg; //'用户名不能为空'
      this.cache.push(() => {
        const strategy = strategyAry.shift() || ''; //用户挑选的strategy
        strategyAry.unshift(value); //把input的value添加进参数列表
        strategyAry.push(errorMsg); //把errorMsg添加进参数列表，[dom.value,6,errorMsg]
        return strategies[strategy].apply(null, strategyAry);
      });
    }
  }
  public start() {
    for (const validatorFunc of this.cache) {
      const errorMsg = validatorFunc(); //开始校验，并取得校验后的返回信息
      if (errorMsg) {
        //r如果有确切返回值，说明校验没有通过
        return errorMsg;
      }
    }
    return '';
  }
}
